<template>
<div>

<el-card class="box-card">
<div slot="header" class="clearfix">
    <span>订单列表</span>
</div>

	<el-row>

	<el-form :inline="true" :model="form" >
		<el-form-item >
			<daterange v-bind:se.sync="s_e" type="daterange"></daterange>
	    </el-form-item>

	    <!-- <el-form-item >
		    <el-date-picker
		      v-model="g"
		      type="date"
		      placeholder="出游日期">
		    </el-date-picker>
		</el-form-item> -->

		<el-form-item >
		    <el-input v-model="form.ticket_code" placeholder="票码"></el-input>
		</el-form-item>

	    <el-form-item >
		    <el-input v-model="form.title" placeholder="订单名称"></el-input>
		</el-form-item>

		<el-form-item >
		    <el-input v-model="form.name" placeholder="游客姓名"></el-input>
		</el-form-item>

		<el-form-item >
		    <el-input v-model="form.mobile" placeholder="下单电话"></el-input>
		</el-form-item>

		<el-form-item >
		    <el-input v-model="form.code" placeholder="订单编号"></el-input>
		</el-form-item>
		
		<el-form-item >
		    <el-select v-model="form.ticket_state"  placeholder="出票状态">
		      <el-option 
		      v-for="item in label.ticketState"
		      :label="item.label" :value="item.value"></el-option>
		    </el-select>
		</el-form-item>
		<el-form-item >
		    <el-select v-model="form.usedstate"  placeholder="使用状态">
		      <el-option
		      	v-for="item in label.usedState"
		       :label="item.label" :value="item.value"></el-option>
		    </el-select>
		</el-form-item>

		<el-form-item>
		    <el-button type="primary" @click="onSubmit">查询</el-button>
		</el-form-item>

    </el-form>
    </el-row>

  	<el-row>
	<el-table
    :data="orderlist.results"
    border
    v-loading="loading"
    style="width: 100%" >
    	<el-table-column type="expand">
	      <template slot-scope="props">
	        <el-form 
	        v-for="item in props.row.ticketlist"
	        label-position="left" inline >
	          <el-form-item>
	            <div>
	            	{{ item.place_name }} / {{ item.type_name }} 
	            </div>

	            <div class="info h5">
	            	有效期：{{ item.period_start }} - {{ item.period }}
	            </div>
	          </el-form-item>

	          <el-form-item>
	            <span class="success" v-if="item.state == '1'">可用</span>
	            <span class="danger" v-if="item.state == '0' && item.used == '1'">已使用</span>
	            <span class="warning" v-if="item.state == '0' && item.back == '1'">已退</span>

	            [{{ item.otime }}]
	          </el-form-item>

	          <el-form-item v-if="item.state == '1'" >
	            <el-button plain type="primary" size="mini" @click="openDeviceList(item)">核销</el-button>
	          </el-form-item>

	          <!-- <el-form-item v-if="item.state == '1' && props.row.myproduct == '0'" >
	            <el-button plain type="primary" size="mini" @click="openDeviceList(item)">核销</el-button>
	          </el-form-item>

	          <el-form-item v-if="props.row.myproduct == '1'" >
	          	系统产品，不能核销
	          </el-form-item> -->
	
	        </el-form>
	      </template>
	    </el-table-column>
	    <el-table-column
	      label="订单信息"
	      width="350">
	      	<template slot-scope="scope">
	      		<div>订单名称：<strong>{{scope.row.title}}</strong></div>
	      		<div>型号名称：{{scope.row.attr_name}}</div>
	      		<div>订单编号：{{scope.row.code}}</div>
	      		<div>产品编号：{{scope.row.product_code}}</div>
	      		<div>
		      		{{label.backState[parseInt(scope.row.profit_state)]}} / 
		      		{{label.payState[parseInt(scope.row.pay_state)]}} / 
		      		{{label.ticketState.filter((item) => {
		      			return item.value == scope.row.ticket_state;
		      		})[0].label}} /
		      		{{label.smsState[parseInt(scope.row.sms_state)]}}
	      		</div>
	      		<div class="red" v-if="scope.row.ticket_state == '9'">
	      			失败原因：{{scope.row.cancel_reason}}
	      		</div>
	      	</template>
	    </el-table-column>

	    <el-table-column
	      label="用户信息"
	      width="250">
	      	<template slot-scope="scope">
	      		<div><strong>{{scope.row.name}} [{{scope.row.mobile}}] </strong></div>
	      		<div v-if="scope.row.cardno != undefined">
	      			身份证：<span>{{scope.row.cardno}}</span>
	      		</div>
	      		<div v-if="scope.row.group != undefined">
	      			出游时间：<span>{{scope.row.group}}</span>
	      		</div>
	      		<div>下单时间：<span>{{scope.row.create_time}}</span></div>
	      		<div v-if="scope.row.remark != undefined && scope.row.remark != '' ">
	      			买家留言：<span class="red">{{scope.row.remark}}</span>
	      		</div>
	      		<div>
	      			卖家备注：<span class="red">{{scope.row.seller_remark}}</span>
	      			<span class="pointer" @click="editRemark(scope.row)"><i class="el-icon-edit "></i></span>
	      		</div>
	      	</template>
	    </el-table-column>

	    <el-table-column
	      label="电子票信息"
	      width="250">
	      	<template slot-scope="scope">
	      		<div>票码：<span>{{scope.row.order_unique_code}}</span></div>
	      		<div>购票数量：<span>{{scope.row.num}}</span></div>
	      		<div>使用数量：<span>{{scope.row.used}}</span></div>
	      		<div>退票数量：<span>{{scope.row.back}}</span></div>
	      		<div>出票时间：<span>{{scope.row.ticket_out_time}}</span></div>
	      	</template>
	    </el-table-column>


	    <el-table-column
	      label="支付信息"
	      width="350">
	      	<template slot-scope="scope">
	      		<div>产品单价：<span>{{scope.row.guide_price}}</span></div>
	      		<div>支付金额：<span>{{scope.row.pay_fee}}</span></div>
	      		<div>支付微信：<span>
	      		<!-- <img :src="scope.row.uid_headimg" width="18" height="18"> -->
	      		{{scope.row.uid_nickname}}</span></div>
	      		<div>支付流水号：<span>{{scope.row.pay_trade_no}}</span></div>
	      		<div>支付时间：<span>{{scope.row.pay_time}}</span></div>
	      	</template>
	    </el-table-column>


	    <el-table-column
	      label="分佣信息"
	      width="350">
	      	<template slot-scope="scope">
	      		<div>一级分销商：<span>{{scope.row.nickname}}</span></div>
	      		<div>一级分佣：<span>{{scope.row.profit}}</span></div>
	      		<div>二级分销商：<span>{{scope.row.nickname1}}</span></div>
	      		<div>二级分佣：<span>{{scope.row.profit1}}</span></div>
	      		<!-- <div>分佣时间：<span>{{scope.row.ticket_out_time}}</span></div> -->
	      	</template>
	    </el-table-column>

	    <el-table-column
	      fixed="right"
	      label="操作"
	      width="100"
	      >
	      <template slot-scope="scope">

	        <el-button v-if="scope.row.profit_state == '0' && scope.row.num - scope.row.used - scope.row.back > 0" 
	        @click="handleClick(scope.row)" type="primary" size="mini">
	        退票</el-button>
	        <br>
	        <span class="h6" v-if="scope.row.sms_state == '1'">发送中</span>
	        <!-- <el-button v-if="scope.row.sms_state == '2' || scope.row.sms_state == '3'"
	         type="text" size="small" @click="resendSMS(scope.row)">重发短信</el-button> 
	         <br>-->
	         <el-button v-if="scope.row.sms_state == '2'"
	         type="warning" size="mini" @click="showSMS(scope.row)">短信</el-button>

	      </template>
	    </el-table-column>
	</el-table>
	</el-row>	


	<el-row class="text-right mt20 mb20">
	<el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next"
      :total="orderlist.totalRecord">
    </el-pagination>
    </el-row>
</el-card>


<el-dialog title="设备列表" :visible.sync="deviceListVisible">
	
	<el-alert
    title="强制核销是，无视当前电子票的限制，直接核销掉，请慎重使用。"
    type="info"
    :closable="false">
    </el-alert>

  <el-table :data="deviceList">
    <el-table-column property="code" label="设备号" width="150"></el-table-column>
    <el-table-column property="remark" label="备注" width="200"></el-table-column>
    <el-table-column label="操作">
    	<template slot-scope="scope">
	        <el-button type="info" size="small" 
	        @click="destroy(scope.row, 0)">核销</el-button>
	        <el-button type="danger" size="small"
	        @click="destroy(scope.row, 1)">强制核销</el-button>
	    </template>
    </el-table-column>
  </el-table>
</el-dialog>


<el-dialog
  title="退票"
  :visible.sync="backOrderDialogVisible"
  width="30%">
  	<el-form ref="backOrderForm" :rules="rules2"
		:model="backOrderForm" 
		label-width="120px"
		>
		<el-form-item label="退票数量：" prop="num" >
			<el-input v-model="backOrderForm.num">
		    </el-input>
		</el-form-item>
		
		<el-form-item class="mt10">
		     <el-button type="primary" 
		     @click="createBackOrder(backOrderForm.num, 'device')">
		     确认</el-button>
		</el-form-item>

	</el-form>	
  
</el-dialog>


<el-dialog
  title="短信"
  :visible.sync="SMSDialogVisible"
  width="90%">
	<el-table
      :data="smsInfoList"
      style="width: 100%">
      
      <el-table-column
        prop="content"
        label="信息"
        >
      </el-table-column>
      <el-table-column
        prop="create_time"
        label="发送时间"
        width="180">
      </el-table-column>
      <!-- <el-table-column
        prop="code"
        label="code"
        width="80">
      </el-table-column> -->
      <el-table-column
        width="80"
        label="发送状态">
        <template slot-scope="scope">
	        <span v-if="scope.row.state == '1'">成功</span>
	        <span v-if="scope.row.state == '0'">失败</span>
	    </template>
      </el-table-column>
      <el-table-column
        width="80"
        label="字数">
        <template slot-scope="scope">
	        {{scope.row.content.length}}
	    </template>
      </el-table-column>
    </el-table>
  <span slot="footer" class="dialog-footer">
  	<el-button type="primary" @click="resendSMS()">重发短信</el-button>
    <el-button @click="SMSDialogVisible = false">取 消</el-button>
  </span>
</el-dialog>


<el-dialog
  title="卖家备注"
  :visible.sync="RemarksVisible"
  width="40%">
  <el-form label-width="100px">

	  <el-form-item label="卖家备注：" >
	    <el-input v-model="currentOrder.seller_remark" style="width:300px;"></el-input>
	  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="RemarksVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRemark">保存</el-button>
  </span>
</el-dialog>


</div>
</template>

<script>

import { mapGetters } from 'vuex'
import { date2str, dateDiff } from '../../config/util'
import daterange from '../../components/daterange'

export default {
	name: 'orderlist',
	data () {

		var validateNum = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('请输入退票数量'));
			} else {

				const max = parseInt(this.backOrder.num) - parseInt(this.backOrder.used) - parseInt(this.backOrder.back);

				if(!/^[0-9]+$/.test(value)) {
					callback(new Error('请输入数字'));
				} else if(value <= 0){
					callback(new Error('请输入大于0的数'));
				} else if(value > max){
					callback(new Error('最多可以退 ' + max));
				}else {
					callback();
				}
			}
		};

		return {
		  	form : {
				title : '',
				code : '',
				mobile : '',
				name : '',
				ticket_state : '',
				usedstate : '',
				ticket_code : '',
			},
			pageNo : 1,
			pageSize : 10,
			totalRecord : 0,
			totalPage : 0,

			loading : true,

			g : '',
			s_e : [date2str(new Date()), date2str(new Date())],

			label : {
				backState : ['随时退', '不可退'],
				payState : ['未支付', '已支付'],
				smsState : ['不发短信', '未发送短信', '已发送短信', '短信发送异常'],
				ticketState : [
					{'label' : '查询全部', 'value' : ''},
					{'label' : '未出票', 'value' : '0'},
					{'label' : '出票中', 'value' : '1'},
					{'label' : '出票完成', 'value' : '2'},
					{'label' : '出票失败', 'value' : '9'},
				],
				usedState : [
					{'label':'查询全部','value':''},
					{'label':'未使用','value':'1'},
					{'label':'已使用','value':'6'},
					{'label':'全部使用','value':'2'},
					{'label':'部分使用','value':'3'},
					{'label':'已退款','value':'7'},
					{'label':'全部退款','value':'4'},
					{'label':'部分退款','value':'5'},
				]
			},

			deviceListVisible : false,

			deviceList : [],

			destroyCode : '',

			backOrderDialogVisible : false,

			backOrderForm : {
				num : 0,
			},

			rules2: {
	          num: [
	            { validator: validateNum, trigger: 'blur' }
	          ],
	        },

	        backOrder : {},

	        SMSDialogVisible : false,

	        orderlist : {},

	        seller_remark_flag : 0,

	        RemarksVisible : false,

	        currentOrder : {},

	        smsInfoList : [],

	        currentSmsOrder : {},

		}
	},

	components: {

		daterange,
	},

	computed : {
		...mapGetters([
			//'orderlist',
			'userInfo',
		]),
	},

	methods : {
		
		getOrderList () {

			console.log(this.s_e);

			var para = {
				pageNo : this.pageNo,
				pageSize : this.pageSize,
				title : this.form.title,
				code : this.form.code,
				mobile : this.form.mobile,
				//group : this.g == '' ? '' : date2str(this.g),
				order_unique_code : this.form.ticket_code,
				name : this.form.name,
				ticket_state : this.form.ticket_state,
				usedstate : this.form.usedstate,
				start_time : this.s_e[0] + ' 00:00:00',
				end_time : this.s_e[1] + ' 23:59:59',
				cb : (data) => {
					this.orderlist = data;
					this.loading = false;
				},
				err : res => {
					this.loading = false;
					this.$notify.error({
			          title: '错误',
			          message: res,
			        });
				}
			};

			this.loading = true;
			this.$store.dispatch('getOrderList', para);
		},

		handleClick (item) {
			this.backOrder = item;
			this.backOrderDialogVisible = true;

		},

		onSubmit () {
			this.getOrderList();
		},

		handleSizeChange (val) {
			this.pageSize = val;
			this.getOrderList();
		},

		handleCurrentChange (val) {
			this.pageNo = val;
			this.getOrderList();
		},


		openDeviceList (item) {

			this.deviceListVisible = true;

			console.log(item);

			this.destroyCode = item.code;

			let para = {
				fun : 'deviceList',
				view : item.place_code,
				cb : res => {
					console.log(res);

					if(res.length == 0){
						console.log()
						//如果商家下面没有设备，用这个机构编号+商家编号 创建一个。
						var para1 = {
				            'code' : this.userInfo.company_code + item.place_code,
				            'pas' : '000000',
				            'view' : item.place_code,
				            'remarks' : '默认创建',
				            cb : res => {
				            	this.deviceList.push({
				            		code : this.userInfo.company_code + item.place_code,
				            		remarks : '默认创建',
				            	});
				            }
				        };

				        this.$store.dispatch('updateDevice', para1);
					}else{
						this.deviceList = res;
					}
					
				}
			};

			this.$store.dispatch('query', para);
			
		},

		destroy (item, what) {
			console.log(item);
			console.log(what);

			let para = {
				fun : 'queryByCode',
				code : this.destroyCode,
				device : item.code,
				force : what,
				cb : res => {
					console.log(res);

					this.$confirm('确认要核销这个票码吗?', '提示', {
			          confirmButtonText: '确定',
			          cancelButtonText: '取消',
			          type: 'warning'
			        }).then(() => {
			          	let para1 = {
							fun : 'destroyByCode',
							code : this.destroyCode,
							device : item.code,
							num : 1,
							reqkey : res.reqkey,
							force : what,
							cb : res1 => {
								console.log(res1);

								this.getOrderList();

								this.deviceListVisible = false;

							},
							err : res1 => {
								this.$message.error(res1);
							}
						};

						this.$store.dispatch('update', para1);
			        }).catch(() => {
			                   
			        });
				},
				err : res => {
					this.$message.error(res);
				}
			};

			this.$store.dispatch('update', para);

		},

		//重发短信
		resendSMS () {

			if(this.currentSmsOrder.code == undefined){
				return;
			}

			const order_create_time = this.currentSmsOrder.create_time.split(' ')[0];

			const dday = dateDiff('2019-01-07', order_create_time);

			if(dday < 0){
				this.$message('2019年1月7日之前的短信，不能重发。');
				return;
			}

			const para = {
				fun : 'resendSMS',
				ordercode : this.currentSmsOrder.code,
				cb : res => {
					console.log(res);
					this.$notify({
			          title: '成功',
			          message: res,
			          type: 'success'
			        });

			        this.currentSmsOrder = {};
			        this.SMSDialogVisible = false;
				}
			};

			this.$store.dispatch('update', para);
		},


		createBackOrder () {

			this.$refs['backOrderForm'].validate((valid) => {
				if (valid) {

					const para = {
						fun : 'backOrder',
						back_count : this.backOrderForm.num,
						order_code : this.backOrder.code,
						cb : res => {
							console.log(res);

							this.$notify({
					          title: '成功',
					          message: '退票成功',
					          type: 'success'
					        });
							this.getOrderList();
					        this.backOrderDialogVisible = false;
						},
						err : res => {
							this.$notify({
					          title: '失败',
					          message: res,
					          type: 'error'
					        });
						}
					};

					console.log(para);

					this.$store.dispatch('update', para);

				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},


		showSMS (item) {
			console.log(item);

			const para = {
				'fun' : 'getSmsInfo',
				'order_code' : item.code,
				cb : res => {
					console.log(res);
					this.SMSDialogVisible = true;
					this.smsInfoList = res;
					this.currentSmsOrder = item;
				}

			};

			this.$store.dispatch('update', para);
			
		},


		editRemark (item) {
			console.log(item);
			this.RemarksVisible = true;
			this.currentOrder = item;
		},

		saveRemark () {
			const para = {
				fun : 'modifyOrderSellerRemark',
				id : this.currentOrder.id,
				seller_remark : this.currentOrder.seller_remark,
				cb : res => {
					console.log(res);
					this.currentOrder = {};
					this.RemarksVisible = false;
					this.$notify({
			          title: '成功',
			          message: '保存成功',
			          type: 'success'
			        });
					//item.isEditing = false;
					this.getOrderList();
				}
			};
			this.$store.dispatch('update', para);
		},
	},

	watch:{
	    
	},

	mounted () {
		
		this.getOrderList();
	},

}
</script>

<style scoped>

</style>
